#include "StdAfx.h"
#include "ServerMng.h"
#include <fstream>


ServerInfoEx::ServerInfoEx( net::network_t link, xgc_byte kind, s_uuid uuid, xgc_byte group, xgc_lpcstr address, xgc_uint16 port )
	//: mImpl( xgc_nullptr )
	: mUsage( 0 )
{
	this->kind = kind;
	this->group = group;
	memcpy( this->address, address, sizeof(this->address) );
	this->port = port;

	this->uuid = uuid;
	mLink = link;
}

ServerInfoEx::ServerInfoEx( xgc_byte kind, s_uuid uuid )
{
	this->uuid = uuid;
	this->kind = kind;
}

CServerMng::CServerMng(void)
{
}

CServerMng::~CServerMng(void)
{
}

Json::Value* CServerMng::ReadConfig( xgc_lpcstr filename )
{
	std::ifstream ifs( filename );
	if( ifs.is_open() )
	{
		Json::Reader mReader;
		if( mReader.parse( ifs, mRoot ) == false )
		{
			cout 
				<< "parse config file 'config.json' error" << endl 
				<< mReader.getFormatedErrorMessages().c_str() << endl;
			mRoot.clear();
		}

		ifs.close();

		return &mRoot;
	}

	return xgc_nullptr;
}

xgc_int32 CServerMng::InsertServer( net::network_t link, xgc_byte kind, const ServerInfoEx** info )
{
	Json::Value Node = mRoot[mRoot["TableIndex"][kind].asString()];

	if( Node.isNull() )
		return -3;
	
	ServerInfoSet::_Pairib ib;
	if( Node["ServerType"] == "Multiple" )
	{
		ServerInfoList ServerList;
		ServerMng::Instance().GetServerList( (enServerDefine)kind, ServerList );
		if( Node["ListenPort"].size() <= ServerList.size() )
			return -2;

		ib = mServerSet.insert( ServerInfoEx( link, kind, Node["UUID"].asUInt() + ServerList.size(), Node["Group"].asUInt(), Node["ListenAddr"].asCString(), Node["ListenPort"][ServerList.size()].asUInt() ) );
	}
	else if( Node["ServerType"] == "Single" )
	{
		ib = mServerSet.insert( ServerInfoEx( link, kind, Node["UUID"].asUInt(), Node["Group"].asUInt(), Node["ListenAddr"].asCString(), Node["ListenPort"].asUInt() ) );
	}

	if( ib.second && info)
	{
		*info = &(*ib.first);
	}

	return ib.second?0:-1;
}

xgc_void CServerMng::RemoveServer( xgc_byte uuid )
{
	for( ServerInfoSet::iterator info = mServerSet.begin(); info != mServerSet.end(); ++info )
	{
		if( info->uuid == uuid )
		{
			mServerSet.erase( info );
			return;
		}
	}
}